# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name:        Security.py
# Purpose:
#
# Author:      Drago@
#
# Created:     11.08.2009
# Copyright:   (c) Drago@ 2009
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import Pyro.core

from pygs.interfaces import ISecurityInterface, IPersistenceInterface, BaseService
from pygs.logger import logger

import time

class Security(BaseService, Pyro.core.ObjBase, ISecurityInterface):
    """
        Security service implementation
    """

    # Session expirationTime in minutes
    expirationTime = 30

    def __init__(self):
        Pyro.core.ObjBase.__init__(self)

    def startup(self, params = None):
        BaseService.startup(self, params)
        # get expirationTime from params
        if params and params.has_key("expirationTime"):
            self.expirationTime = params["expirationTime"]

    def shutdown(self):
        BaseService.shutdown(self)
        pass

    def login(self, params):
        # TODO check params
        userName = params["user"]
        passwd = params["passwd"]
        logger.log("Try to login user '%s'." % userName)
        # calc expiration date
        expirationDate = time.strftime("%Y-%m-%d %X", time.localtime(time.time() + self.expirationTime * 60))
        logger.debug("Calculated expiration date: '%s'." % expirationDate)
        # get new user token
        token = self.getServiceProvider().implementation(IPersistenceInterface).getToken(
            userName, passwd, expirationDate)
        logger.log("Got token '%s' for user '%s'. Token expire: %s." %
            (token, userName, expirationDate))
        return token

    def logout(self, token):
        # TODO check params
        res = self.getServiceProvider().implementation(IPersistenceInterface).deleteToken(token)
        logger.log("Token '%s' deleted." % token)
        return res

    def hasRigths(self, token, rightType):
        # TODO check params
        res = self.getServiceProvider().implementation(IPersistenceInterface).hasRight(token, rightType)
        return res

    def isSessionExpired(self, token):
        res = self.getServiceProvider().implementation(IPersistenceInterface).isSessionExpired(token)
        return res
